﻿using System;
using System.Collections.Generic;
using YinLongTool.Extensions;
using YinLongTool.Text;

namespace YinLongTool.Net.Http
{
	public class RequestItemBuilder
	{
		public List<RequestItem> items
		{
			get;
			private set;
		}

		public bool AllowKeyDuplicate
		{
			get;
			set;
		}

		public bool EncodeKey
		{
			get;
			set;
		}

		public RequestItemCaseType CaseType
		{
			get;
			set;
		}

		public RequestItemBuilder()
		{
			items = new List<RequestItem>();
			AllowKeyDuplicate = true;
		}

		public RequestItemBuilder Add(string key, string value = "", RequestItemCaseType caseType = RequestItemCaseType.Default)
		{
			bool flag = false;
			if (!AllowKeyDuplicate)
			{
				foreach (RequestItem item in items)
				{
					if (item.Key == key)
					{
						flag = true;
						item.Value = value;
					}
				}
			}
			if (!AllowKeyDuplicate && flag)
			{
				return this;
			}
			items.Add(new RequestItem
			{
				Key = key,
				Value = value,
				CaseType = caseType
			});
			return this;
		}

		public string GenQueryString(string codePage = "utf-8")
		{
			string text = "";
			foreach (RequestItem item in items)
			{
				if (text.Length > 0)
				{
					text += "&";
				}
				string text2 = EncodingUtil.UrlEncode(item.Value, codePage);
				string text3 = item.Key;
				if (EncodeKey)
				{
					text3 = EncodingUtil.UrlEncode(text3, codePage);
				}
				if (CaseType == RequestItemCaseType.Lower)
				{
					text2 = text2.ToLower();
				}
				if (CaseType == RequestItemCaseType.Upper)
				{
					text2 = text2.ToUpper();
				}
				if (CaseType == RequestItemCaseType.Default)
				{
					if (item.CaseType == RequestItemCaseType.Lower)
					{
						text2 = text2.ToLower();
					}
					if (item.CaseType == RequestItemCaseType.Upper)
					{
						text2 = text2.ToUpper();
					}
				}
				text += $"{text3}={text2}";
			}
			return text;
		}

		public void RemoveItem(string key)
		{
			for (int num = items.Count - 1; num >= 0; num--)
			{
				if (items[num].Key.ToLower() == key.ToLower())
				{
					items.RemoveAt(num);
				}
			}
		}

		public string GetItemValue(string key)
		{
			foreach (RequestItem item in items)
			{
				if (item.Key.ToLower() == key.ToLower())
				{
					return item.Value;
				}
			}
			return "";
		}

		public void SetItemValue(string key, string value)
		{
			foreach (RequestItem item in items)
			{
				if (item.Key.ToLower() == key.ToLower())
				{
					item.Value = value;
				}
			}
		}

		public void SetItemValue(int index, string value)
		{
			if (items.Count - 1 >= index)
			{
				items[index].Value = value;
			}
		}
	}

}
